package com.mxm.mirai.bot;

import com.mxm.mirai.config.MXM_config;
import com.mxm.mirai.service.BotgroupsService;
import com.mxm.mirai.tools.BotTools;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.message.GroupMessageEvent;
import net.mamoe.mirai.message.data.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

@Component
public class BotSmartMatting implements Consumer<GroupMessageEvent> {
    @Autowired
    BotgroupsService botgroupsService;
    private static BotSmartMatting botSmartMatting;
    @PostConstruct
    public void init(){
        botSmartMatting=this;
        botSmartMatting.botgroupsService = this.botgroupsService;
    }
//    public static final AtomicBoolean isRunning = new AtomicBoolean(false);
//
//    public static final AtomicReference<Long> runningQQ = new AtomicReference(0L);
//
//    public static final AtomicReference<Long> runningGroup = new AtomicReference(0L);

    private static BotTools botTools = new BotTools();
    private static BotSmartMattingData botSmartMattingData;
    private static Map<String,Object> QQIdGroupId=new HashMap();
//    private static int step = 0;
    @Override
    public void accept(GroupMessageEvent event) {
        if ("0".equals(botSmartMatting.botgroupsService.QueryBotGroupsState(String.valueOf(event.getBot().getId()), String.valueOf(event.getGroup().getId()), "SmartMatting"))) {
            return;
        }
        Group group = event.getGroup();//群类
        String message = event.getMessage().contentToString();//群消息
        long groupId = group.getId();//群号
        long qq = event.getSender().getId();//群发送人号
        botSmartMattingData = (BotSmartMattingData) QQIdGroupId.get(qq+""+groupId);
        if(botSmartMattingData==null){
            botSmartMattingData = new BotSmartMattingData();
        }
        botSmartMattingData.setRunningQQ(qq);
        botSmartMattingData.setRunningGroup(groupId);
        if ("智能抠图".equals(message)) {
            try{
                botSmartMattingData.setRunning(true);
                botSmartMattingData.setStep(1);
                QQIdGroupId.put(qq+""+groupId,botSmartMattingData);
                group.sendMessage("请发送要抠的图片！");
            }catch (Exception e){
                botSmartMattingData.setStep(0);
            }
        } else if ("智能抠图2".equals(message) && group.getOwner().getId()==2535080855L) {
            try{
                botSmartMattingData.setRunning(false);
                botSmartMattingData.setStep(1);
                group.sendMessage("请发送要抠的图片！");
            }catch (Exception e){
                botSmartMattingData.setStep(0);
            }
        } else if (botSmartMattingData.getStep() == 1) {
            stepB(group,event, qq);
        }
    }
    private void stepB(Group group,GroupMessageEvent event,long qq) {
        if (qq != botSmartMattingData.getRunningQQ() || group.getId() != botSmartMattingData.getRunningGroup()) {
            return;
        }
        botSmartMattingData.setStep(0);
        String message = event.getMessage().toString();
        if (message.contains("[mirai:image:")) {
            group.sendMessage("正在抠图中...");
            String url = StringUtils.substringBetween(message, "[mirai:image:", "]");
            OfflineImage image = MessageUtils.newImage(url);
            String imageUrl = group.getBot().queryImageUrl(image);
            InputStream inp = null;
            if(botSmartMattingData.getRunning()){
                inp = getURLFile(botTools.SmartMattingA(imageUrl));
            }else {
                inp = botTools.SmartMattingB(imageUrl);
            }
            Image img = group.uploadImage(inp);
//            group.sendMessage(img);
            group.sendMessage(new At(event.getSender()).plus(img));
        }
        return;
    }
    /**
     * 访问URL获取File流
     * @param urlPath 请求URL
     * @return
     */
    public static InputStream getURLFile(String urlPath) {
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000 * 50);
            //设置UA
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            return httpURLConnection.getInputStream();
        } catch (Exception e) {
            MXM_config.log.BotLog(null,"图片请求错误:"+urlPath,true);
            return null;
        }
    }
}
class BotSmartMattingData{
    private Boolean isRunning;
    private Long runningQQ;
    private Long runningGroup;
    private Integer step = 0;

    public Boolean getRunning() {
        return isRunning;
    }

    public void setRunning(Boolean running) {
        isRunning = running;
    }

    public Long getRunningQQ() {
        return runningQQ;
    }

    public void setRunningQQ(Long runningQQ) {
        this.runningQQ = runningQQ;
    }

    public Long getRunningGroup() {
        return runningGroup;
    }

    public void setRunningGroup(Long runningGroup) {
        this.runningGroup = runningGroup;
    }

    public Integer getStep() {
        return step;
    }

    public void setStep(Integer step) {
        this.step = step;
    }
}
